package com.hzit.filter;

import cn.hutool.core.util.StrUtil;
import com.hzit.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：登录过滤器
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("过滤器初始化.");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//0. 定义放行的白名单
		List<String> whiteList = Arrays.asList("/user?cmd=login","/login.jsp");
		//1. 得到请求的路径，除了ip与端口之外，后面的内容，如：http://localhost:9000/user？cmd=list,处理后得到/user
		String requestURI = req.getRequestURI();        // /与？号之间的内容
		String queryString = req.getQueryString();      // ？号的参数
		String urlInfo = requestURI;
		if(StrUtil.isNotBlank(queryString)){
			urlInfo += "?" + queryString;
		}
		if(whiteList.contains(urlInfo)){       // 如果是当前请求地址是登录，则放行
			chain.doFilter(req,resp);
		}else{
			//2. 得到session
			HttpSession session = req.getSession();
			//3. 从session中取得登录用户
			User user = (User) session.getAttribute("user");
			//4. 如果登录用户为null，证明未登录
			if(user == null){
				resp.sendRedirect("/login.jsp");
			}else{   // 说明用户名密码都是成功的，曾经登录成功
				chain.doFilter(req,resp);
			}
		}

	}

	@Override
	public void destroy() {

	}
}
